<template>
    <section id="withdraw">
      <Base-UserMoneyInfo :type="type" :refresh.sync="refresh"></Base-UserMoneyInfo>
      <div class="money_list">
        <div class="title">提现金额</div>
        <ul>
          <li :class="index === tabIndex ? 'active' : ''" v-for="(item,index) in moneyList" :key="index" @click="tabIndex=index;withdrawMoney=''">
            <div>${{item.money}}</div>
            <div v-if="lists">≈ {{(Math.floor(Number(item.money)*Number(lists.new_price)*100)/100).toFixed(2)}}元</div>
            <div v-else>≈ {{(Math.floor(Number(item.money)*defaultRate*100)/100).toFixed(2)}}元</div>
          </li>
        </ul>
        <div class="customize_money" v-if="moneyList" :class="tabIndex === moneyList.length && 'active'" @click="tabIndex = moneyList.length">
          <input type="text" maxlength="10"  v-model="withdrawMoney" placeholder="输入金额" @input="clearNoNum(withdrawMoney)">
          <span v-if="lists">≈ {{(Math.floor(Number(Number(withdrawMoney).toFixed(2))*Number(lists.new_price)*100)/100).toFixed(2)}}元</span>
          <span v-else>≈ {{(Math.floor(Number(Number(withdrawMoney).toFixed(2))*defaultRate*100)/100).toFixed(2)}}元</span>
        </div>
      </div>
      <ul class="tips">
        <li>1.每日只能提现一次</li>
        <li>2.出金时间周一至周五9:00~16:00，T+0资金到达节假日顺延</li>
        <li>3.出金手续费收取{{fees}}%</li>
        <li>4.请认真填写您的每一项提现信息</li>
      </ul>
      <div class="card_selected">
        <div class="title">选择银行卡</div>
        <div class="list" v-if="cardList && cardList.length > 0">
          <div class="item" v-for="(item,index) in cardList" :key="index" :class="item.class">
            <div class="top">
              <span>{{item.name}}</span>
              <span>{{item.bank_mobile | phoneFormat}}</span>
            </div>
            <div class="middle"><span>****</span><span>****</span><span>****</span>{{item.bank_number | bankCardFormat}}</div>
            <div class="bottom">
              <span>{{item.bank_name}}{{item.bank_branch}}</span>
            </div>
            <div class="out">
              <span>卡{{index+1}}</span>
              <input type="radio" name="card" :id="'card'+index" @change="radioIndex = index">
              <label :for="'card'+index"></label>
            </div>
          </div>
          <div class="add" @click="toAddBank=true">
            <div>+</div>
            <div>添加</div>
          </div>
        </div>
        <div class="card_input" v-else>
          <div class="input_group">
            <label for="name">姓&nbsp;&nbsp;&nbsp;名：</label>
            <base-input
              id="chinaName"
              placeholder="请输入持卡人姓名"
              v-model="formData.name"
              :rules="rules.chinaName"
              @error="showError($event)"
            ></base-input>
            <div class="error" v-show="errorMsg.chinaName"><img src="../../assets/image/icon_tishi.png">{{errorMsg.chinaName}}</div>
          </div>
          <div class="input_group">
            <label for="tel">手机号：</label>
            <base-input
              id="tel"
              :type="types.tel"
              placeholder="请输入持卡人银行预留的手机号"
              v-model="formData.tel"
              :rules="rules.tel"
              @error="showError($event)"
              maxlength="11"
            ></base-input>
            <div class="error" v-show="errorMsg.tel"><img src="../../assets/image/icon_tishi.png">{{errorMsg.tel}}</div>
          </div>
          <div class="input_group">
            <label for="card">身份证：</label>
            <base-input
              id="idCard"
              placeholder="请输入持卡人身份证号码"
              v-model="formData.card"
              :rules="rules.idCard"
              @error="showError($event)"
              maxlength="18"
            ></base-input>
            <div class="error" v-show="errorMsg.idCard"><img src="../../assets/image/icon_tishi.png">{{errorMsg.idCard}}</div>
          </div>
          <div class="input_group">
            <label for="bankCard">银行卡：</label>
            <base-input
              id="bankCard"
              placeholder="请输入银行卡号"
              v-model="formData.bankCard"
              :rules="rules.bankCard"
              @error="showError($event)"
              @input="changeCard"
              maxlength="23"
            ></base-input>
            <div class="error" v-show="errorMsg.bankCard"><img src="../../assets/image/icon_tishi.png">{{errorMsg.bankCard}}</div>
          </div>
          <div class="input_group">
            <label for="bank">开户行：</label>
            <base-input
              id="bankName"
              placeholder="请输入开户行名称"
              v-model="formData.bank"
              :rules="rules.bankName"
              @error="showError($event)"
            ></base-input>
            <div class="error" v-show="errorMsg.bankName"><img src="../../assets/image/icon_tishi.png">{{errorMsg.bankName}}</div>
          </div>
          <div class="input_group">
            <label for="area">地&nbsp;&nbsp;&nbsp;区：</label>
            <base-input
              id="bankArea"
              placeholder="请输入银行卡所在地区，如北京"
              v-model="formData.area"
              :rules="rules.bankArea"
              @error="showError($event)"
            ></base-input>
            <div class="error" v-show="errorMsg.bankArea"><img src="../../assets/image/icon_tishi.png">{{errorMsg.bankArea}}</div>
          </div>
          <div class="input_group">
            <label for="bankName">支&nbsp;&nbsp;&nbsp;行：</label>
            <base-input
              id="branchBank"
              placeholder="请输入开户行支行"
              v-model="formData.bankName"
              :rules="rules.branchBank"
              @error="showError($event)"
            ></base-input>
            <div class="error" v-show="errorMsg.branchBank"><img src="../../assets/image/icon_tishi.png">{{errorMsg.branchBank}}</div>
          </div>
        </div>
        <div class="button">
          <button class="btn_private" @click="toWithdraw">确认</button>
        </div>
      </div>
      <base-alert :bol.sync="toSetBundsPw" :type="3" title="设置"></base-alert>
      <base-alert :bol.sync="toAddBank" :type="7" @addBankEvent='add($event)'></base-alert>
      <base-alert :bol.sync="checkBundsPw" :type='11' @zjpw='submitWithdraw($event)'></base-alert>
    </section>
</template>
<script>
import {_getWithdrawMoneyList,_getBankCardList,_getConf,_hadSetBundPw,_submitWithdraw,_addBankCard,_getUserInfo,_getWithdrawRate} from '../../axios/index.js';
export default {
  data() {
    return {
      show:true,// 余额是否显示
      tabIndex:0,// 金额列表index
      moneyList:[],
      withdrawMoney:'',
      defaultRate:6.75,
      checkBundsPw:false, // 验证资金密码
      cardList:[],
      type:2,// 充值为1，提现为2
      show1:false,
      fees:'',
      toSetBundsPw:false,
      formData:{
        name:'',
        card:'',
        tel:'',
        bankCard:'',
        bank:'',
        bankName:'',
        area:''
      },
      maxMoney:null,
      minMoney:null,
      disabled:false, // 是否禁止提交
      refresh:false,// 是否刷新可提现金额
      radioIndex:null, // 银行卡列表index
      toAddBank:false,
      
      rules: {
        tel: [
          { required: true, msg: "请输入手机号码" },
          {
            reg: /^(0|86|17951)?(13[0-9]|15[012356789]|17[012345678]|18[0-9]|14[56789]|19[0-9]|16[0-9])[0-9]{8}$/,
            msg: "手机号码格式不正确"
          }
        ],
        chinaName:[
          {required:true,msg:"请输入姓名"},
          {
            reg:/^([\u4e00-\u9fa5\·]{2,10})$/,
            msg:'姓名格式不正确'
          }
        ],
        idCard:[
          {required:true,msg:"请输入身份证号码"},
          {
            reg:/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/,
            msg:'身份证号码格式不正确'
          }
        ],
        bankCard:[
          {required:true,msg:"请输入银行卡号码"}
        ],
        bankName:[
          {required:true,msg:"请输入开户行名称"},
        ],
        branchBank:[
          {required:true,msg:"请输入开户行支行"},
        ],
        bankArea:[
          {required:true,msg:"请输入开户行地区"},
        ]
      },
      errorId:'',
      errorMsg: {
        chinaName:"",
        idCard:"",
        tel:"",
        bankCard:"",
        bankName:"",
        branchBank:"",
        bankArea:""
      },
      types: {
        tel: "tel",
        number: "number",
        password: "password"
      },
    }
  },
  computed:{
    lists() {
      let _self = this;
      // let lists = this.$store.state.symbolList;
      // if (lists) {
      //   for (let i = 0; i < lists.length; i++) {
      //     for (let j = 0; j < lists[i]["goods_list"].length; j++) {
      //       if (lists[i]["goods_list"][j]["id"] == 16) {
      //         let new_price =
      //           lists[i]["goods_list"][j]["inAndOut"]["new_price"];
      //         return {
      //           new_price: new_price
      //         };
      //       }
      //     }
      //   }
      // }
      return {
        new_price:_self.defaultRate
      }
    }
  },
  methods:{
    async getRate() {
      const res = await _getWithdrawRate();
      if (res.data.code === 200) {
        this.defaultRate = res.data.data;
      }
    },
    clearNoNum(val){ 
      var len=13;
      val = val.replace(/[^\d.]/g,"");  //清除“数字”和“.”以外的字符
      val = val.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的  
      val = val.replace(".","$#$").replace(/\./g,"").replace("$#$","."); 
      val = val.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');//只能输入两个小数  
      if(val.indexOf(".")< 0 && val !=""){//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额 
          val = parseFloat(val); 
          len=10;
      }
     
      this.withdrawMoney = val;   
    },
    bankCardFormat(value) {
      value = value.replace(/ /g,'');
      let arr = value.split('');
      let newArr = [];
      for (let i = 0; i < arr.length; i+=4) {
        newArr.push(arr.slice(i,i+4).join(''));
      }
      let newValue = '';
      newValue = newArr.join(' ');
      return newValue;
    },
    changeCard() {
      this.formData.bankCard = this.bankCardFormat(this.formData.bankCard);
      let newCard = this.formData.bankCard.replace(/ /g,'');
      let url = 'https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo='+newCard+'&cardBinCheck=true';
      if (newCard.length == 15 || newCard.length == 19) {
        this.axios({
          method:'get',
          url:url
        }).then((res)=>{
          if (res.data.validated) {
            this.formData.bankName = this.$js.getBankName(res.data.bank)
          }
        })
      }
    },
    async getWithdrawMoneyList() {
      const res = await _getWithdrawMoneyList();
      if (res.data.code === 200) {
        this.moneyList = res.data.data;
      }
    },
    async getBankCardList() {
      const res = await _getBankCardList();
      if (res.data.code === 200) {
        this.cardList = res.data.data;
      }
    },
    async getFees() {
      const res = await _getConf('out_money_gas');
      if (res.data.code === 200) {
        this.fees = res.data.data;
      }
    },
    async getMoneyMax() {
      const res = await _getConf('out_money_max');
      if (res.data.code === 200) {
        this.maxMoney = res.data.data;
      }
    },
    async getMoneyMin() {
      const res = await _getConf('out_money_min');
      if (res.data.code === 200) {
        this.minMoney = res.data.data;
      }
    },
    async addBank() {
      let params = {
        name:this.formData.name,  // 开户人姓名
        bank_number:this.formData.bankCard.replace(/ /g,''), // 银行账号
        bank_name:this.formData.bank, // 开户行名称
        bank_branch:this.formData.bankName, // 支行
        bank_mobile:this.formData.tel, // 银行预留手机号
        id_card:this.formData.card, // 身份证
        bank_area:this.formData.area, // 开户行地区
      };
      const res = await _addBankCard(params);
      if (res.data.code === 200) {
        this.queryBankList();
      } else {
        this.$Message.error(res.data.msg);
      }
    },
    async queryBankList() {
      const res = await _getBankCardList();
      if (res.data.code === 200) {
        let cardList =  res.data.data;
        let classList = ['bg_blue','bg_green','bg_purple'];
        let result = [],newResult=[];
        for (let i = 0; i < cardList.length; i+=3) {
          result.push(cardList.slice(i,i+3));
        }
        for (let j = 0; j < result.length; j++) {
          for (let k = 0; k < result[j].length; k++) {
            result[j][k].class = classList[k];
            newResult.push(result[j][k]);
          }
        }
        this.cardList = newResult;
      } else {
        this.$Message.error(res.data.msg);
        return;
      }
    },
    /**
     * 检测用户是否设置了资金密码
     */
    async hadSetBundPw() {
      let _self = this;
      let userType = _self.$store.state.user_type;
      const res = await _hadSetBundPw(userType);
      if (res.data.code === 200 && res.data.msg === '未设置') {
        _self.toSetBundsPw = true;
        _self.disabled = true;
      } else if (res.data.code === 200 && res.data.msg === '已设置') {
        _self.toSetBundsPw = false;
        _self.disabled = false;
      }
    },
    isWeekend() {
      let date = new Date();
      let day = date.getDay();
      let hours = date.getHours();
      let tips = '出金时间为周一至周五9:00~16:00';
      
      
      if (day === 0 || day === 6) {
        // 周末不能提现
        this.$Message.error(tips);
          this.checkBundsPw = false;
        return;
      } else {
        if (hours < 9 || hours >= 16) {
          this.$Message.error(tips);
          this.checkBundsPw = false;
          return;
        } else {
          this.checkBundsPw = true;
        }
      }
    },
    toWithdraw() {
      let _self = this;
      _self.hadSetBundPw();
      if (_self.disabled){
        return;
      }
      if (this.cardList.length > 0) {
        if (this.radioIndex == null) {
          this.$Message.error('请选择银行卡');
          return;
        }
        this.formData.name = this.cardList[this.radioIndex].name;
        this.formData.card = this.cardList[this.radioIndex].id_card;
        this.formData.bankCard = this.cardList[this.radioIndex].bank_number.replace(/ /g,'');
        this.formData.bank = this.cardList[this.radioIndex].bank_name;
        this.formData.area = this.cardList[this.radioIndex].bank_area;
        this.formData.bankName = this.cardList[this.radioIndex].bank_branch;
        this.formData.tel = this.cardList[this.radioIndex].bank_mobile;
      }
      let testBankCard = this.formData.bankCard.replace(/ /g,'');
      if (!/^\d{15,20}$/.test(testBankCard)) {
        this.$Message.error('银行卡格式有误');
        document.getElementById('bankCard').focus();
        return;
      }
      let withdrawMoney = _self.withdrawMoney ? _self.withdrawMoney : (_self.tabIndex != _self.moneyList.length ? _self.moneyList[_self.tabIndex].money : '');
        if (_self.formData.name && _self.formData.card && _self.formData.tel && _self.formData.bankCard 
        && _self.formData.bank && _self.formData.bankName && _self.formData.area
        &&!_self.errorMsg.chinaName && !_self.errorMsg.idCard && !_self.errorMsg.tel && !_self.errorMsg.bankCard && !_self.errorMsg.bankName
        && !_self.errorMsg.branchBank && !_self.errorMsg.bankArea) {
          if(Number(withdrawMoney) > Number(this.maxMoney) || Number(withdrawMoney) < Number(this.minMoney)){
            this.$Message.error('金额不能小于'+this.minMoney+'或大于'+this.maxMoney);
            return;
          }
          if (_self.chooseIndex == _self.moneyList.length && withdrawMoney && Number(withdrawMoney) <= 0) {
            this.$Message.error('金额不能小于0');
            return;
          } else if (_self.chooseIndex == _self.moneyList.length && !withdrawMoney) {
            this.$Message.error('金额不能为空');
            return;
          }
          _self.isWeekend();
        } else {
            this.$Message.error('请正确填写所有信息');
        }
    },
    showError(data) {
      let _self = this;
      _self.errorMsg[data.id] = data.msg;
      if (!data.msg) {
        _self.errorMsg[data.id] = "";
      }
    },
    /**
     * 提现接口
     */
    async submitWithdraw(pw) {
      let _self = this;
      let user = _self.$store.state.user;
      let phone = '';
      if (user) {
        phone = user.mobile;
      }
      let money = '';
      if (_self.tabIndex < _self.moneyList.length) {
        money = _self.moneyList[_self.tabIndex].money;
      } else if (_self.tabIndex == _self.moneyList.length) {
        money = Number(_self.withdrawMoney).toFixed(2); // 提现金额(美元)
      }
      //md5(md5(密码)账号)
      let md5Pw =_self.$md5((_self.$md5(pw)+phone));
      let id_card = _self.formData.card, // 身份证号
            name = _self.formData.name, // 收款人姓名
            bank_number = _self.formData.bankCard.replace(/ /g,''), // 银行卡号
            bank_name = _self.formData.bank, // 开户银行
            addr = _self.formData.area,// 地区
            bank_branch = _self.formData.bankName, // 支行
            mon_password = md5Pw,
            bank_mobile = _self.formData.tel; // 银行卡绑定手机号
      const data = {
        money:money,
        id_card:id_card,
        name:name,
        bank_number:bank_number,
        bank_name:bank_name,
        addr:addr,
        bank_branch:bank_branch,
        mon_password:mon_password,
        bank_mobile:bank_mobile
      };
      const res = await _submitWithdraw(data);
      if (res.data.code === 200) {
        this.$Message.success(res.data.msg);
        if (this.cardList.length == 0) {
          this.addBank();
        }
        this.refresh =  true;
      } else {
        this.$Message.error(res.data.msg);
      }
    },
    async add(data) {
      const res = await _addBankCard(data);
      if (res.data.code === 200) {
        this.alertBankBol = false;
        this.$Message.success(res.data.msg);
        this.queryBankList();
      } else {
        this.$Message.error(res.data.msg);
      }
    },
  },
  created() {
    //获取用户信息
    this.$store.dispatch("getUser");
    this.$emit('title','提现');
    this.getRate();
    this.getWithdrawMoneyList();
    this.queryBankList();
    this.getFees();
    this.getMoneyMax();
    this.getMoneyMin();
    this.hadSetBundPw();
  }
}
</script>
